<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, FormRules, UploadUserFile } from "element-plus"
import { listDatatype, getCatalogType } from "@@/apis/basic-type"
import { ModelDetailData } from "@@/apis/component/types"
import { ref, onMounted, watch, defineExpose, defineEmits  } from "vue"
interface BasicTypeInfo {
  id?: string;
  value: string;
  label: string;
}
const props = defineProps<{
  dialogVisible: boolean
  detailData: object
  fieldsType: string
}>()

const emit = defineEmits(['closeDialog', 'handleConfirm'])

const closeDialog = () => {
  if (props.dialogVisible) {
    emit('closeDialog')
  }
}

const handleCloseTip = () => {
  closeDialog()
}

const textMap = ref('新增参数集')
const ruleFormRef = ref<FormInstance | undefined>(undefined)
const formData = ref<ModelDetailData>({
  code: '',
  name: '',
  type: 'base',
  separator: '',
  recordType: '',
  typeId: '', // 数据类型id
  typeCode: '', // 数据类型value
  staticFlag: 0 // 是否静态
})
const formMethodsData = ref({
  type: '',
  returnType: '',
  name: '',
  separator: ''
})
const formMethodsRules = ref({
  type: [
    { required: true, message: '请选择类型', trigger: 'blur' }
  ],
  returnType: [
    { required: true, message: '请输入返回类型', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入函数名称', trigger: 'blur' }
  ]
})
const loading = ref(false)
const formRules = ref({
  code: [
    { required: true, message: '请输入参数名', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入参数描述', trigger: 'blur' }
  ],
  recordType: [
    { required: true, message: '请选择数据类型', trigger: 'blur' }
  ],
  separator: [
    { required: true, message: '请输入参数连接符', trigger: 'blur' }
  ]
})
const ruleFormMethodsRef = ref<FormInstance | undefined>(undefined)
const handleConfirm = async () => {
  if (props.fieldsType === 'fields') {
    if (!ruleFormRef.value) return false
    return await ruleFormRef.value
      .validate()
      .then((valid) => {
        emit('handleConfirm', formData.value, 'fields')
      }).catch(() => {
        return false
      })
  } else {
    if (!ruleFormMethodsRef.value) return false
    return await ruleFormMethodsRef.value
      .validate()
      .then((valid) => {
        emit('handleConfirm', formMethodsData.value, 'methods')
      }).catch(() => {
        return false
      })
  }

}

interface RowData {
  id: string;
}

const currentRow = ref('')
const tableData = ref<BasicTypeInfo[]>([])
const textBtn = ref('编辑')
const createUpdate = ref('')
const tableRef = ref<any>(null)
const tableClass = ref<BasicTypeInfo[]>([])
const tableEnum = ref<BasicTypeInfo[]>([])
const tableBase = ref<BasicTypeInfo[]>([])
const getRowKeys = (row: any) => row.id
const handleSelectionChange = (selection: any) => {
}
onMounted(() => {
  function digui(params: any) {
    if (params && params.length > 0) {
      params.forEach((item: any) => {
        if (item.tag === 'enum') {
          item.value = item.struct ? item.struct.code : ''
          item.label = item.struct ? item.struct.name : ''
          item.description = item.struct ? item.struct.description : ''
          tableEnum.value.push(item)
        } else if (item.tag === 'class') {
          item.value = item.struct ? item.struct.code : ''
          item.label = item.struct ? item.struct.name : ''
          item.description = item.struct ? item.struct.description : ''
          tableClass.value.push(item)
        } else if (item.tag === 'folder' && item.children && item.children.length > 0) {
          digui(item.children)
        }
      })
    }
  }
  listDatatype({}).then((res) => {
    tableBase.value = res.data
    tableData.value = res.data
  })
  getCatalogType().then((res) => {
    digui(res.data)
    // tableData.value = res.data
  })
})
const handleCurrentChange = (row: any) => {
  formData.value.typeId = row.id
  formData.value.typeCode = row.value
}
// // 更新表格数据
watch(() => formData.value.type, (newType) => {
  if (newType === 'enum') {
    tableData.value = tableEnum.value
  } else if (newType === 'class') {
    tableData.value = tableClass.value
  } else {
    tableData.value = tableBase.value
  }
})
// // 编辑|| 查看 || 新增
watch(() => props.detailData, (newDetailData) => {
  if (props.fieldsType === 'fields') {
    formData.value = JSON.parse(JSON.stringify(newDetailData))
    currentRow.value = (newDetailData as any).typeId // 使用类型断言来避免类型错误
    createUpdate.value = JSON.parse(JSON.stringify(newDetailData)).code
  } else if (props.fieldsType === 'methods') {
    formMethodsData.value = JSON.parse(JSON.stringify(newDetailData))
    createUpdate.value = JSON.parse(JSON.stringify(newDetailData)).name
  }
},{immediate: true, deep: true})
defineExpose({
  formData
})
const textBtnClick = () => {
  if (textBtn.value === '编辑') {
    textBtn.value = '详情'
  } else {
    textBtn.value = '编辑'
  }
}
</script>
<template>
  <el-drawer
    :model-value="dialogVisible"
    @update:model-value="$emit('closeDialog')"
    direction="rtl"
    size="800px"
    :destroy-on-close="true"
    :show-header="false"
    @close-auto-focus="closeDialog"
    @close="closeDialog"
    :before-close="handleCloseTip"
  >
    <template #header>
      <h4>{{ textMap }}</h4>
      <span class="drawer-header-text" v-if="createUpdate" @click="textBtnClick">{{ textBtn }}</span>
    </template>
    <template #default v-if="fieldsType === 'fields'">
      <el-form
          v-if="!createUpdate || textBtn === '详情'"
          ref="ruleFormRef"
          :model="formData"
          status-icon
          append-to-body
          :rules="formRules"
          label-position="top"
          label-width="auto"
          class="demo-ruleForm">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item prop="code" label="参数名">
                <el-input v-model="formData.code" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="name" label="参数描述">
                <el-input v-model="formData.name" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item prop="recordType" label="数据类型">
                <el-select popper-class="drawer-select-popper" v-model="formData.recordType" placeholder="请选择" style="width: 100%">
                  <el-option label="基本类型" value="1" />
                  <el-option label="数组类型" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="separator" label="参数连接符">
                <el-input v-model="formData.separator" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item>
                <el-radio-group v-model="formData.type">
                  <el-radio value="base" size="large">基本类型</el-radio>
                  <el-radio value="enum" size="large">数据结构（枚举）</el-radio>
                  <el-radio value="class" size="large">数据结构（类）</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-if="createUpdate && textBtn === '编辑'" class="drawer-content-detail mt-12" >
          <el-row class="drawer-content" :gutter="10">
            <el-col :xs="6" :sm="2"> 参数名 </el-col>
            <el-col :xs="18" :sm="2"> {{ formData.code }} </el-col>
            <el-col :xs="12" :sm="3"> 参数描述: </el-col>
            <el-col :xs="18" :sm="2"> {{ formData.name }} </el-col>
            <el-col :xs="6" :sm="3"> 数据类型: </el-col>
            <el-col :xs="18" :sm="3"> {{ formData.recordType === '1' ? '基本类型' : '数组类型' }} </el-col>
          </el-row>
          <el-row class="drawer-content" :gutter="10">
            <el-col :xs="6" :sm="4"> 参数连接符: </el-col>
            <el-col :xs="18" :sm="2"> {{ formData.separator }} </el-col>
          </el-row>
        </div>
        <el-table
          ref="tableRef"
          :data="tableData"
          v-loading="loading"
          :row-key="getRowKeys"
          @selection-change="handleSelectionChange"
        >
          <el-table-column width="35">
            <template #default="scope">
              <el-radio
                v-model="currentRow"
                :label="scope.row.id"
                @change="handleCurrentChange(scope.row)"
                class="radio-custom"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="formData.type !== 'base'" prop="text" label="所属目录" header-align="left" />
          <el-table-column prop="value" label="标识" header-align="left" />
          <el-table-column prop="label" label="辅助标识" header-align="left" />
          <el-table-column v-if="formData.type !== 'base'" prop="description" show-overflow-tooltip label="描述" header-align="left" />
        </el-table>
    </template>
    <template #default v-if="fieldsType === 'methods'">
      <el-form
          v-if="!createUpdate || textBtn === '详情'"
          ref="ruleFormMethodsRef"
          :model="formMethodsData"
          status-icon
          append-to-body
          :rules="formMethodsRules"
          label-position="top"
          label-width="auto"
          class="demo-ruleForm">
          <el-row :gutter="24" justify="center">
            <el-col :span="12">
              <el-form-item prop="type" label="类型">
                <el-select popper-class="drawer-select-popper" v-model="formMethodsData.type" placeholder="请选择" style="width: 100%">
                  <el-option label="normal" value="normal" />
                  <el-option label="virtual" value="virtual" />
                  <el-option label="static" value="static" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" justify="center">
            <el-col :span="12">
              <el-form-item prop="returnType" label="返回类型">
                <el-input v-model="formMethodsData.returnType" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" justify="center">
            <el-col :span="12">
              <el-form-item prop="name" label="函数名称">
                <el-input v-model="formMethodsData.name" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-if="createUpdate && textBtn === '编辑'" class="drawer-content-detail mt-12" >
          <el-row class="drawer-content" :gutter="10" justify="center">
            <el-col :xs="6" :sm="3"> 类 型: </el-col>
            <el-col :xs="18" :sm="3"> {{ formMethodsData.type }} </el-col>
          </el-row>
          <el-row class="drawer-content" :gutter="10" justify="center">
            <el-col :xs="6" :sm="3"> 返回类型: </el-col>
            <el-col :xs="18" :sm="3"> {{ formMethodsData.returnType }} </el-col>
          </el-row>
          <el-row class="drawer-content" :gutter="10" justify="center">
            <el-col :xs="6" :sm="3"> 函数名称: </el-col>
            <el-col :xs="18" :sm="3"> {{ formMethodsData.name }} </el-col>
          </el-row>
        </div>
    </template>
    <template #footer>
      <div class="dialog-footer" v-if="!createUpdate || textBtn === '详情'">
        <el-button
          :loading="loading"
          type="primary"
          @click.stop="handleConfirm"
        >保 存</el-button>
        <el-button plain @click="closeDialog">退 出</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<style lang="scss" scoped>
.upload-demo {
  width: 100% !important;
}
:deep(.el-upload.el-upload--text) {
  width: 100% !important;
}
:deep(.el-table) {

  .el-radio__label {
    display: none;
  }
}
:deep(.el-radio__input.is-checked .el-radio__inner) {
  background: var(--el-color-primary);
  border-color: var(--el-color-primary);
}
.drawer-content-detail {
  color: #000;
  .drawer-content {
    >.el-col:first-child {
      text-align: left;
    }
  }
}
.drawer-header-text {
    width: 136px;
    height: 28px;
    font-size: 12px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    background: #F5F7FA;
    border: 1px solid #DCDFE6;
    cursor: pointer;
    border-radius: 4px 4px 4px 4px;
}
</style>
